﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HttpService
{
    /// <summary>
    /// http server.
    /// </summary>
	public class HttpServer
	{
		TcpListener server;
		Thread accept_thread;
		Queue<HttpTask> tasks = new Queue<HttpTask>();

		public int QueueCount { get { return tasks.Count; } }

		public HttpServer(int port) : this(IPAddress.Any, port)
		{
		}

		public HttpServer(IPAddress ip, int port)
		{
			server = new TcpListener(ip, port);
			server.Start();
			accept_thread = new Thread(()=>{
				while(true)RequestHandler(server.AcceptSocket());
			});
			accept_thread.Start();
		}

		public HttpTask PopTask()
		{
			if (tasks.Count > 0)
				return tasks.Dequeue();
			else
				return null;
		}

		public void RequestHandler(Socket sock)
		{
			new Thread((arg) =>
			{
				var socket = arg as Socket;
				try
				{
					Request req = new Request(socket);
					Response res = new Response(socket);
					tasks.Enqueue(new HttpTask(req, res));
				}
				catch
				{
				}
			}).Start(sock);
		}
	}

    /// <summary>
    /// http task
    /// </summary>
	public class HttpTask
	{
		public Request Request;// http request
		public Response Response;// http request for write

		public HttpTask(Request req, Response res)
		{
			Request = req;
			Response = res;
		}
	}

}
